package com.lwlk.zdk.controller;

import com.alibaba.fastjson.JSONObject;
import com.lwlk.zdk.annotation.JwtIgnore;
import com.lwlk.zdk.annotation.MyLog;
import com.lwlk.zdk.common.UserOnlineListener;
import com.lwlk.zdk.mapper.T.TDisPlatformMapper;
import com.lwlk.zdk.enums.RetCode;
import com.lwlk.zdk.mapper.pw.pwLoginTimeMapper;
import com.lwlk.zdk.mapper.pw.pwUserMapper;
import com.lwlk.zdk.mapper.sys.sysUserMapper;
import com.lwlk.zdk.model.Audience;
import com.lwlk.zdk.model.pw.pwLoginTime;
import com.lwlk.zdk.util.*;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.lwlk.zdk.util.SessionUtil.dateToStamp;

/**
 * ========================
 * Created with IntelliJ IDEA.
 * User：pyy
 * Date：2019/7/18 10:41
 * Version: v1.0
 * ========================
 */
@Slf4j
@RestController
public class AdminUserController {

    @Autowired
    pwLoginTimeMapper loginTimeMapper;
    @Autowired
    TDisPlatformMapper disPlatformMapper;
    @Autowired
    pwUserMapper userMapper;


    @ApiOperation(value = "用户登录")
    @MyLog(value = "登录信息")  //这里添加了AOP的自定义注解
    @PostMapping("/login")
    @JwtIgnore
    public Response adminLogin(HttpServletResponse response, String userName, String password, HttpSession httpSession) {
        Response response1=new Response();
        //String pwd= MD5Utils.encrypt(userName,password);

        List<Map<String,Object>> platformList=userMapper.selectOne(userName);
        //List<Map<String,Object>> platform=disPlatformMapper.selectOne(Integer.parseInt(String.valueOf(platformList.get(0).get("platformId"))));
        /*if (platform.size()==0){
            response1.setCode(RetCode.PLATFORM_NOTEXIST);
            return response1;
        }*/
        if (platformList.size()==0){//账号未存在
            response1.setCode(RetCode.ACCOUNT_NULL);
            return response1;
        }
        if (!password.equals(platformList.get(0).get("password"))){//密码错误
            response1.setCode(RetCode.PWD_ERROR);
            return response1;
        }
        if (Integer.parseInt(String.valueOf(platformList.get(0).get("isForbidden")))==0){
            response1.setCode(RetCode.PWD_ERROR);
            response1.setMsg("该账号已被禁用");
            return response1;
        }
        //获取用户ip地址
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        // 这里模拟测试, 默认登录成功，返回用户ID和角色信息
       // String userId = UUID.randomUUID().toString();
       // String role = "admin";
        Audience audience=new Audience();
        audience.setBase64Secret("MDk4ZjZiY2Q0NjIxZDM3M2NhZGU0ZTgzMjYyN2I0ZjY=");
        audience.setClientId(IPUtils.getIpAddr(request));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date=new Date();
        String sessionId=dateToStamp(sdf.format(date));
        audience.setExpiresSecond(Integer.parseInt(sessionId));
        audience.setName(String.valueOf(platformList.get(0).get("name")));

        // 创建token
        String token = JwtTokenUtil.createJWT(String.valueOf(platformList.get(0).get("id")), userName, "admin", audience);
        //log.info("### 登录成功, token={} ###", token);

        httpSession.setAttribute("platformUser", platformList);
        String tokenId=token.replaceAll("Bearer ","");
        httpSession.setAttribute("userOnlineListener", new UserOnlineListener(tokenId));
        log.info("当前登录用户的sessionId"+httpSession.getId());

        int count=loginTimeMapper.selectOne(httpSession.getId());
        pwLoginTime pwLoginTime=new pwLoginTime();
        pwLoginTime.setPlatformId(Integer.parseInt(String.valueOf(platformList.get(0).get("id"))));
        pwLoginTime.setLoginTimeInt(new Date());
        pwLoginTime.setSessionId(token);
        if (count==0){
            loginTimeMapper.insertSelective(pwLoginTime);
        }else {
            loginTimeMapper.updateLoginTime(pwLoginTime);
        }

        // 将token放在响应头
        response.setHeader(JwtTokenUtil.AUTH_HEADER_KEY, JwtTokenUtil.TOKEN_PREFIX + token);
        // 将token响应给客户端
        JSONObject result = new JSONObject();
        result.put("token", JwtTokenUtil.TOKEN_PREFIX + token);
        result.put("platformName",platformList.get(0).get("name"));//平台名称
        result.put("uId",platformList.get(0).get("id"));//平台名称
        result.put("paltformCode",platformList.get(0).get("regionCode"));//区域码
        //result.put("accessCode",platform.get(0).get("accessCode"));//接入码
        result.put("paltformUsername",userName);//账号
        result.put("platformPassword",password);
        result.put("platformId",platformList.get(0).get("id"));
        //result.put("regionId",platform.get(0).get("regionId"));
        result.put("parentId",platformList.get(0).get("parentId"));//登陆账号所在地区的父节点
        result.put("level",platformList.get(0).get("level"));//账号等级:用户登录区域级别（1省、2市、3县）
        response1.setData(result);
        response1.setCode(RetCode.SUCCESS);
        response1.setMsg("执行成功");
        return response1;
    }
}
